﻿using System;
using System.Composition;
using System.Windows.Input;
using Unread.App.Common;
using Unread.Business.Services.Interfaces;
using Windows.UI.ViewManagement;

namespace Unread.App.ViewModels
{
    [Export]
    public class OpmlViewModel : BindableBase
    {
        private readonly IFeedsImporter _feedsImporter;
        private readonly IFeedsExporter _feedsExporter;

        private bool _isLoading;
        public bool IsLoading
        {
            get { return _isLoading; }
            set { SetProperty(ref _isLoading, value); }
        }

        [ImportingConstructor]
        public OpmlViewModel(IFeedsImporter feedsImporter, IFeedsExporter feedsExporter)
        {
            if (feedsImporter == null) throw new ArgumentNullException("feedsImporter");
            if (feedsExporter == null) throw new ArgumentNullException("feedsExporter");

            _feedsImporter = feedsImporter;
            _feedsExporter = feedsExporter;

            ImportFeedsCommand = new DelegateCommand(ImportFeeds, CanImportFeeds);
            ExportFeedsCommand = new DelegateCommand(ExportFeeds, CanExportFeeds);
        }

        #region ImportFeedsCommand

        public ICommand ImportFeedsCommand { get; private set; }

        private bool CanImportFeeds(object arg)
        {
            return !IsLoading && IsUnsnapped();
        }

        private async void ImportFeeds(object obj)
        {
            IsLoading = true;

            await _feedsImporter.Import();

            IsLoading = false;
        }

        #endregion

        #region ExportFeedsCommand

        public ICommand ExportFeedsCommand { get; private set; }

        private bool CanExportFeeds(object arg)
        {
            return !IsLoading && IsUnsnapped();
        }

        private async void ExportFeeds(object obj)
        {
            IsLoading = true;

            await _feedsExporter.Export();

            IsLoading = false;
        }

        #endregion

        private static bool IsUnsnapped()
        {
            return ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());
        }
    }
}
